<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>共享出行 - 支付中心</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        
        .header {
            background-color: #007bff;
            color: white;
            padding: 0 20px;
            height: 50px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            font-size: 1.2rem;
        }
        .nav-buttons {
            display: flex;
            gap: 10px;
        }
        .nav-button {
            background: transparent;
            border: 1px solid rgba(255, 255, 255, 0.5);
            border-radius: 4px;
            color: white;
            padding: 6px 12px;
            cursor: pointer;
            transition: background-color 0.2s;
            font-size: 14px;
        }
        .nav-button:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .username {
            margin-right: 15px;
            font-size: 14px;
        }
        
        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
        }
        
        .payment-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .payment-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.05);
            overflow: hidden;
            transition: transform 0.2s;
        }
        
        .payment-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.1);
        }
        
        .payment-header {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            background: #f9f9f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .payment-header h3 {
            margin: 0;
            font-size: 1.2rem;
            color: #333;
        }
        
        .status-tag {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .status-paid {
            background: #e8f5e9;
            color: #2e7d32;
        }
        
        .status-unpaid {
            background: #ffebee;
            color: #c62828;
        }
        
        .payment-body {
            padding: 20px;
        }
        
        .trip-details {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .trip-info {
            flex: 2;
            min-width: 250px;
        }
        
        .trip-cost {
            flex: 1;
            min-width: 200px;
            background: #f5f9ff;
            padding: 15px;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px dashed #eee;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .cost-row {
            display: flex;
            justify-content: space-between;
        }
        
        .total-cost {
            font-size: 1.4rem;
            font-weight: bold;
            color: #f57c00;
            padding-top: 10px;
            margin-top: 10px;
            border-top: 2px solid #e1e1e1;
        }
        
        .action-buttons {
            margin-top: 20px;
            text-align: right;
        }
        
        .button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 600;
        }
        
        .button-primary {
            background: #007bff;
            color: white;
        }
        
        .button-primary:hover {
            background: #0056b3;
        }
        
        .button-secondary {
            background: #e0e0e0;
            color: #333;
            margin-right: 10px;
        }
        
        .button-secondary:hover {
            background: #ccc;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .empty-state h3 {
            margin-bottom: 10px;
            font-size: 1.4rem;
        }
        
        /* 支付模态框样式 */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s, visibility 0.3s;
        }
        
        .modal.show {
            opacity: 1;
            visibility: visible;
        }
        
        .modal-content {
            background: white;
            width: 90%;
            max-width: 500px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
            transform: translateY(20px);
            transition: transform 0.3s;
        }
        
        .modal.show .modal-content {
            transform: translateY(0);
        }
        
        .modal-header {
            padding: 20px;
            background: #f5f5f5;
            border-bottom: 1px solid #e1e1e1;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-header h2 {
            margin: 0;
            font-size: 1.4rem;
            color: #333;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #666;
        }
        
        .modal-body {
            padding: 20px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        
        .form-input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
            box-sizing: border-box;
        }
        
        .form-input:focus {
            border-color: #007bff;
            outline: none;
            box-shadow: 0 0 0 2px rgba(0,123,255,0.2);
        }
        
        .input-group {
            display: flex;
            gap: 10px;
        }
        
        .input-group .form-input {
            flex: 1;
        }
        
        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #e1e1e1;
            background: #f9f9f9;
            text-align: right;
        }
        
        .loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            visibility: hidden;
            opacity: 0;
            transition: opacity 0.3s, visibility 0.3s;
        }
        
        .loading.show {
            visibility: visible;
            opacity: 1;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .toast {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: #4caf50;
            color: white;
            padding: 15px 25px;
            border-radius: 4px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            z-index: 1010;
            opacity: 0;
            transform: translateY(20px);
            transition: opacity 0.3s, transform 0.3s;
        }
        
        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }
        
        .toast.error {
            background: #f44336;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>共享出行系统</h1>
        <div class="nav-buttons">
            <span class="username" id="usernameDisplay"></span>
            <button class="nav-button" onclick="window.location.href='vehicle-list.html'">车辆租赁</button>
            <button class="nav-button" onclick="window.location.href='trip.html'">当前行程</button>
            <button class="nav-button" onclick="window.location.href='edit-profile.html'">个人资料</button>
            <button class="nav-button" onclick="logout()">退出登录</button>
        </div>
    </div>

    <div class="container">
        <div id="paymentList" class="payment-list">
            <!-- 支付列表将通过JavaScript动态生成 -->
        </div>
    </div>

    <!-- 支付模态框 -->
    <div id="paymentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>支付行程费用</h2>
                <button class="modal-close" onclick="closePaymentModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <div class="detail-row">
                        <span>行程费用:</span>
                        <span id="modalTripAmount">¥0.00</span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label" for="cardNumber">卡号</label>
                    <input type="text" id="cardNumber" class="form-input" placeholder="输入16-19位卡号" maxlength="19">
                </div>
                <div class="input-group">
                    <div class="form-group">
                        <label class="form-label" for="expiryDate">有效期 (MM/YY)</label>
                        <input type="text" id="expiryDate" class="form-input" placeholder="MM/YY" maxlength="5">
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="cvv">CVV</label>
                        <input type="text" id="cvv" class="form-input" placeholder="3位安全码" maxlength="3">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="button button-secondary" onclick="closePaymentModal()">取消</button>
                <button class="button button-primary" onclick="processPayment()">确认支付</button>
            </div>
        </div>
    </div>

    <div id="loading" class="loading">
        <div class="spinner"></div>
    </div>

    <div id="toast" class="toast"></div>

    <script>
        let trips = [];
        let currentTripId = null;

        document.addEventListener('DOMContentLoaded', function() {
            checkLogin().then(isLoggedIn => {
                if (isLoggedIn) {
                    fetchUnpaidTrips();
                }
            });
        });

        // 检查登录状态
        async function checkLogin() {
            showLoading();
            try {
                const response = await fetch('api/check-login', {
                    credentials: 'include'
                });
                const result = await response.json();
                hideLoading();
                
                if (!result.success) {
                    window.location.href = 'login.html';
                    return false;
                }
                
                // 显示用户名
                document.getElementById('usernameDisplay').textContent = result.data.username;
                
                return true;
            } catch (error) {
                hideLoading();
                console.error('检查登录状态失败:', error);
                window.location.href = 'login.html';
                return false;
            }
        }

        // 退出登录
        async function logout() {
            try {
                showLoading();
                const response = await fetch('api/logout', {
                    method: 'POST',
                    credentials: 'include'
                });
                const result = await response.json();
                
                hideLoading();
                if (result.success) {
                    window.location.href = 'login.html';
                }
            } catch (error) {
                hideLoading();
                console.error('退出登录失败:', error);
            }
        }

        // 获取未支付的行程
        async function fetchUnpaidTrips() {
            showLoading();
            try {
                const response = await fetch('api/trips/unpaid', {
                    credentials: 'include'
                });
                const result = await response.json();
                hideLoading();
                
                if (result.success) {
                    trips = result.data;
                    renderTripsList();
                } else {
                    showToast(result.message || '获取未支付行程失败', true);
                }
            } catch (error) {
                hideLoading();
                console.error('获取未支付行程失败:', error);
                showToast('获取未支付行程失败，请稍后重试', true);
            }
        }

        // 渲染行程列表
        function renderTripsList() {
            const container = document.getElementById('paymentList');
            
            if (!trips || trips.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <h3>没有待支付的行程</h3>
                        <p>您当前没有任何未支付的行程记录</p>
                        <button class="button button-primary" onclick="window.location.href='vehicle-list.html'">返回首页</button>
                    </div>
                `;
                return;
            }
            
            let html = '';
            
            trips.forEach(trip => {
                const vehicle = trip.vehicle || { brand: '未知', model: '未知', type: '未知', pricePerMinute: 0 };
                const startTime = new Date(trip.startTime).toLocaleString();
                const endTime = new Date(trip.endTime).toLocaleString();
                const durationMinutes = trip.durationMinutes || 0;
                
                html += `
                    <div class="payment-card">
                        <div class="payment-header">
                            <h3>行程 #${trip.id}</h3>
                            <span class="status-tag status-unpaid">待支付</span>
                        </div>
                        <div class="payment-body">
                            <div class="trip-details">
                                <div class="trip-info">
                                    <div class="detail-row">
                                        <span>车辆型号</span>
                                        <span>${getTypeText(vehicle.type)} ${vehicle.brand} ${vehicle.model}</span>
                                    </div>
                                    <div class="detail-row">
                                        <span>开始时间</span>
                                        <span>${startTime}</span>
                                    </div>
                                    <div class="detail-row">
                                        <span>结束时间</span>
                                        <span>${endTime}</span>
                                    </div>
                                    <div class="detail-row">
                                        <span>使用时长</span>
                                        <span>${formatDuration(durationMinutes)}</span>
                                    </div>
                                </div>
                                <div class="trip-cost">
                                    <div class="cost-row">
                                        <span>单价</span>
                                        <span>¥${vehicle.pricePerMinute}/分钟</span>
                                    </div>
                                    <div class="cost-row">
                                        <span>使用时长</span>
                                        <span>${durationMinutes} 分钟</span>
                                    </div>
                                    <div class="cost-row total-cost">
                                        <span>总费用</span>
                                        <span>¥${trip.cost ? trip.cost.toFixed(2) : '0.00'}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="action-buttons">
                                <button class="button button-primary" onclick="openPaymentModal(${trip.id}, ${trip.cost || 0})">支付</button>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }

        // 打开支付模态框
        function openPaymentModal(tripId, amount) {
            currentTripId = tripId;
            document.getElementById('modalTripAmount').textContent = `¥${amount.toFixed(2)}`;
            document.getElementById('paymentModal').classList.add('show');
        }

        // 关闭支付模态框
        function closePaymentModal() {
            document.getElementById('paymentModal').classList.remove('show');
            document.getElementById('cardNumber').value = '';
            document.getElementById('expiryDate').value = '';
            document.getElementById('cvv').value = '';
            currentTripId = null;
        }

        // 处理支付
        async function processPayment() {
            if (!currentTripId) return;
            
            const cardNumber = document.getElementById('cardNumber').value.trim();
            const expiryDate = document.getElementById('expiryDate').value.trim();
            const cvv = document.getElementById('cvv').value.trim();
            
            // 简单的表单验证
            if (!cardNumber || !expiryDate || !cvv) {
                showToast('请填写完整的支付信息', true);
                return;
            }
            
            if (!cardNumber.match(/^\d{16,19}$/)) {
                showToast('请输入正确的卡号（16-19位数字）', true);
                return;
            }
            
            if (!expiryDate.match(/^(0[1-9]|1[0-2])\/\d{2}$/)) {
                showToast('请输入正确的有效期（MM/YY格式）', true);
                return;
            }
            
            if (!cvv.match(/^\d{3}$/)) {
                showToast('请输入正确的CVV（3位数字）', true);
                return;
            }
            
            // 执行支付
            showLoading();
            try {
                const trip = trips.find(t => t.id === currentTripId);
                if (!trip) {
                    throw new Error('未找到对应行程');
                }
                
                const response = await fetch('api/payment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        tripId: currentTripId,
                        amount: trip.cost,
                        cardNumber: cardNumber,
                        expiryDate: expiryDate,
                        cvv: cvv
                    }),
                    credentials: 'include'
                });
                
                const result = await response.json();
                hideLoading();
                
                if (result.success) {
                    showToast('支付成功！');
                    closePaymentModal();
                    
                    // 重新加载行程列表
                    setTimeout(() => {
                        fetchUnpaidTrips();
                    }, 1000);
                } else {
                    showToast(result.message || '支付失败，请重试', true);
                }
            } catch (error) {
                hideLoading();
                console.error('支付处理失败:', error);
                showToast('支付处理出错，请稍后重试', true);
            }
        }

        // 格式化时长显示
        function formatDuration(minutes) {
            if (minutes < 60) {
                return `${minutes} 分钟`;
            } else {
                const hours = Math.floor(minutes / 60);
                const mins = minutes % 60;
                return `${hours} 小时 ${mins} 分钟`;
            }
        }

        // 获取车辆类型文本
        function getTypeText(type) {
            switch (type) {
                case 'car': return '汽车';
                case 'e-bike': return '电动车';
                case 'bicycle': return '自行车';
                default: return type;
            }
        }

        // 显示加载动画
        function showLoading() {
            document.getElementById('loading').classList.add('show');
        }

        // 隐藏加载动画
        function hideLoading() {
            document.getElementById('loading').classList.remove('show');
        }

        // 显示提示信息
        function showToast(message, isError = false) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = 'toast';
            if (isError) toast.classList.add('error');
            
            toast.classList.add('show');
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }
    </script>
</body>
</html> 